<?php

/**
 * 保存用户信息
 *
 * @param unknown $openId
 */
function SaveUserinfo($openId,$token,$qrtype=1){
	$userinfo=WechatAdvanceAPI::GetUserInfo($openId);

	if(!$token){
		$token=session('token');
	}

	if($userinfo->subscribe==1){
		$subscriber=M('subscriber');
		$isnew=false;
		$where['token']=$token;
		$where['openid']=$openId;
		$data=$subscriber->where($where)->find();
		if($data==null){
			$isnew=true;
		}
		$data['token']=$token;
		$data['openid']=$openId;
		$data['nickname']=$userinfo->nickname;
		$data['sex']=$userinfo->sex;
		$data['city']=$userinfo->city;
		$data['country']=$userinfo->country;
		$data['province']=$userinfo->province;
		$data['language']=$userinfo->language;
		$data['headimgurl']=$userinfo->headimgurl;
		$data['addtime']=$userinfo->subscribe_time;
		$data['issubscribe']=$userinfo->subscribe;
		$data['qrtype'] = $qrtype;
			
		if($isnew){
			$subscriber->add($data);
		}else{
			$subscriber->where($where)->save($data);
		}
		return true;
	}else{
		return false;
	}
}

/**
 * 保存取消关注用户信息
 *
 * @param unknown $openId
 */
function SaveUnScribeUserinfo($openId,$token){
	if(!$token){
		$token=session('token');
	}
	$subscriber=M('subscriber');
	$where['token']=$token;
	$where['openid']=$openId;
	$data=$subscriber->where($where)->find();

	if($data!=null){
		$data['issubscribe']=0;
		$subscriber->where($where)->save($data);
	}
}

/**
 * 保存用户分组信息
 * @param unknown $token
 * @return boolean
 */
function SaveGroupInfo($token){
	$gpinfo=WechatAdvanceAPI::GetGroups();
	$gpinfos=$gpinfo->groups;

	if(!$token){
		$token=session('token');
	}
	if($gpinfos){
		$model=M('subscribe_group');
			
		foreach($gpinfos as $gp){
			$isnew=false;
			$where['token']=$token;
			$where['groupid']=$gp->id;
			$data=$model->where($where)->find();
			if($data==null){
				$isnew=true;
			}
			$data['token']=$token;
			$data['groupid']=$gp->id;
			$data['groupname']=$gp->name;
			$data['groupcount']=$gp->count;
			if($isnew){
				$model->add($data);
			}else{
				$model->where($where)->save($data);
			}
		}
		return true;
	}else{
		return false;
	}
}
?>